package com.example.migrator.batch;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class MigrationItemReader extends MyBatisPagingItemReader<Object> {

    private static final Logger logger = LoggerFactory.getLogger(MigrationItemReader.class);
    
    // 存储参数值的成员变量
    private Map<String, Object> parameterValues = new HashMap<>();

    @Autowired
    public MigrationItemReader(@Qualifier("oracleSqlSessionFactory") SqlSessionFactory sqlSessionFactory,
                              @Value("${migrator.batch-size:1000}") int pageSize) {
        setSqlSessionFactory(sqlSessionFactory);
        setQueryId("com.example.migrator.mapper.OracleMapper.selectDataByBatch");
        setPageSize(pageSize);
        setSaveState(true);
    }

    /**
     * 设置要读取的表名
     */
    public void setTableName(String tableName) {
        parameterValues.put("tableName", tableName);
        setParameterValues(parameterValues);
        logger.info("设置读取表名为: {}", tableName);
    }

    /**
     * 设置查询条件
     */
    public void setWhereClause(String whereClause) {
        parameterValues.put("whereClause", whereClause);
        setParameterValues(parameterValues);
        logger.info("设置查询条件: {}", whereClause);
    }
}